package com.genexususa.eo.bing.data.requests;

import com.genexususa.eo.bing.CampaignManagementServiceClasses.AdGroupAdRotation;
import com.genexususa.eo.bing.data.GxItemException;
import com.genexususa.eo.bing.data.wsSubclasses.GxAdGroupAdRotation;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class GxAdGroupAdRotationsRequest {
    private long gxCampaignId;
    private long bingCampaignId;
    private AdGroupAdRotation[] adGroupAdRotations;

    public GxAdGroupAdRotationsRequest(Element element) throws IllegalArgumentException, GxItemException {
        if (element.getElementsByTagName("GxCampaignId").getLength() > 0 &&
            element.getElementsByTagName("GxCampaignId").item(0).getChildNodes().getLength() > 0 &&
            Long.valueOf(((Node)element.getElementsByTagName("GxCampaignId").item(0).getChildNodes().item(0)).getNodeValue()) != 0) {
            this.gxCampaignId = Long.valueOf(((Node)element.getElementsByTagName("GxCampaignId").item(0).getChildNodes().item(0)).getNodeValue());
        } else {
            throw new GxItemException("Missing external Campaign id");
        }
        if (element.getElementsByTagName("BingCampaignId").getLength() > 0 &&
            element.getElementsByTagName("BingCampaignId").item(0).getChildNodes().getLength() > 0 &&
            Long.valueOf(((Node)element.getElementsByTagName("BingCampaignId").item(0).getChildNodes().item(0)).getNodeValue()) != 0) {
            this.bingCampaignId = Long.valueOf(((Node) element.getElementsByTagName("BingCampaignId").item(0).getChildNodes().item(0)).getNodeValue());
        } else {
            throw new GxItemException("Missing Bing Campaign id");
        }
        NodeList adGroupAdRotationsNode = element.getElementsByTagName("AdGroupAdRotationCollection");
        if (adGroupAdRotationsNode.getLength() > 0) {
            NodeList adGroupAdRotationNode = ((Element)adGroupAdRotationsNode.item(0)).getElementsByTagName("AdGroupAdRotation");
            if (adGroupAdRotationNode.getLength() <= 0) {
                throw new GxItemException("No AdGroupAdRotations were found for Campaign " + this.gxCampaignId);
            }
            this.adGroupAdRotations = new AdGroupAdRotation[adGroupAdRotationNode.getLength()];
            for (int i=0; i<adGroupAdRotationNode.getLength(); i++) {
                adGroupAdRotations[i] = new GxAdGroupAdRotation((Element)adGroupAdRotationNode.item(i));
            }
        }
    }

    public long getGxCampaignId() {
        return gxCampaignId;
    }

    public long getBingCampaignId() {
        return bingCampaignId;
    }

    public AdGroupAdRotation[] getAdGroupAdRotations() {
        return adGroupAdRotations;
    }
}
